//
//  MessageListViewController.m
//  HongFuShop
//
//  Created by chirui on 2017/7/25.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "MessageListViewController.h"

@interface MessageListViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>
{
    UITableView * _tableView;
    NSMutableArray * _dataArray;
    int _page;
    int _totailPage;
    
    UIView * noBodyView;
}

@end

@implementation MessageListViewController

-(void)viewWillAppear:(BOOL)animated{
//    _page =1;
//    if (verifTokenAndEnter) {
//         [self getMessageListData];
//        
//    }else{
//        
//        SHuiMBhudTextTimeStr(@"请先登录您的账号！");
//        
//        return;
//    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    TitleView(@"我的消息");
    
    self.view.backgroundColor =[UIColor whiteColor];
    
     [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"img_nav_bg"] forBarMetrics:UIBarMetricsDefault];
//    self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightItemWithIcon:@"icon_nav_empty" target:self action:@selector(deledateBtn)];
    
    [self creatTableView];
    _page= 1;
    _dataArray = @[].mutableCopy;
    noBodyView = [NothingMessageView creatNothingMessageViewFrame:CGRectMake(WIDTH/2-100, (HEIGHT-64)/2-150, 200, 200) andMessageStr:@"没有相关内容！" onView:nil];
    
      [self getMessageListData];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_renter" target:self action:@selector(backBtnClick)];
}

-(void)backBtnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}

//-(void)deledateBtn{
//    
//    if (verifTokenAndEnter) {
//        if (_dataArray.count>0) {
//            
//            UIAlertView *alerte = [[UIAlertView alloc]initWithTitle:nil message:@"确定要清空消息列表吗？" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消",nil];
//            alerte.tag = 1000;
//            [alerte show];
//        }else {
//            
//            [SHJudgeTools MBProgressHUDPromptWith:@"您还没有相关信息!" On:self.view];
//            return;
//            
//        }
//
//    }else{
//    
////        LogingViewController * login =[[LogingViewController alloc]init];
////        login.hidesBottomBarWhenPushed = YES;
////        [self.navigationController pushViewController:login animated:YES];
//    }
//}
//
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//    
//    if (alertView.tag == 1000) {
//        if (buttonIndex == 0) {
//            
//            [self deledateMessageRequestFor:@""];
//        }
//    }
//}
//

-(void)creatTableView {
    
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    UIView * view =[[UIView alloc]init];
    _tableView.tableFooterView = view;
    
    if (@available(iOS 11.0, *)){
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }

    [self.view addSubview:_tableView];
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        if (verifTokenAndEnter) {
            _page = 1;
            [self getMessageListData];
        }else {
            [_tableView.mj_header endRefreshing];
            SHuiMBhudTextTimeStr(@"请先登录您的账号！");
            return;
        }
    }];
    _tableView.mj_header = header;
    MJRefreshAutoNormalFooter *  footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (verifTokenAndEnter) {
            _page ++;
            [self getMessageListData];
        }else {
            [_tableView.mj_footer endRefreshing];
            SHuiMBhudTextTimeStr(@"请先登录您的账号！");
            return;
        }
    }];
    footer.automaticallyRefresh = YES;
    _tableView.mj_footer =footer;
    
    if (_dataArray.count>10) {
        _tableView.mj_footer.hidden = NO;
    }else{
        _tableView.mj_footer.hidden = YES;
    }
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return nil;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _dataArray.count;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary * dic = _dataArray[indexPath.row];
    UILabel * detilsLabel =[[UILabel alloc]initWithFrame:CGRectMake(10, 40, WIDTH -20, 20)];
    detilsLabel.font = [UIFont systemFontOfSize:14];
     detilsLabel.text = dic[@"content"];
    detilsLabel.numberOfLines = 0;
    [detilsLabel sizeToFit];
    
    
    return CGRectGetMaxY(detilsLabel.frame)+35;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //左滑删除
    return UITableViewCellEditingStyleDelete;
    
}
//修改左滑删除按钮的title
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        
        if (verifTokenAndEnter) {
            _page = 1;//
            NSDictionary * dic = _dataArray[indexPath.row];
            [self deledateMessageRequestFor:dic[@"id"]];
        }else{
//            LogingViewController * login =[[LogingViewController alloc]init];
//            login.hidesBottomBarWhenPushed = YES;
//            [self.navigationController pushViewController:login animated:YES];
        }
        
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
    
}



-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    static NSString * cellId = @"cellId";
    
    UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:cellId ];
    if (cell==nil) {
        
        
        cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }else {
        while ([cell.contentView.subviews lastObject] != nil) {
            
            [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
            
        }
    }
    
    cell.contentView.backgroundColor = [UIColor whiteColor];
    
    UIView * view =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
    view.backgroundColor =[UIColor whiteColor];
    
    [cell.contentView addSubview:view];
    NSDictionary * dic = _dataArray[indexPath.row];
   
    
    UILabel * nameLabel =[[UILabel alloc]initWithFrame:CGRectMake(10, 10, WIDTH - 20, 20)];
    nameLabel.text = @"系统消息";
    nameLabel.font = [UIFont systemFontOfSize:15];
    [view addSubview:nameLabel];
    
 
    
    
    UILabel * detilsLabel =[[UILabel alloc]initWithFrame:CGRectMake(10, 40, WIDTH -20, 20)];
    detilsLabel.font = [UIFont systemFontOfSize:14];
    detilsLabel.text = dic[@"content"];
    detilsLabel.numberOfLines = 0;
    [detilsLabel sizeToFit];
    
    UILabel * timeLabel =[[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(detilsLabel.frame)+10, 150, 20)];
    timeLabel.text = dic[@"create_time"];
    timeLabel.textColor = [UIColor grayColor];
    timeLabel.font = [UIFont systemFontOfSize:14];
    [view addSubview:timeLabel];
    
    view.frame = CGRectMake(0, 0, WIDTH , CGRectGetMaxY(detilsLabel.frame)+35);
    
    [view addSubview:detilsLabel];
    
    
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
  
}

-(void)getMessageListData{
    
    
    if (_totailPage != 0) {
        if(_page == _totailPage + 1){
            [_tableView.mj_footer setState: MJRefreshStateNoMoreData];
            
            return ;
        }
    }
    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"page":[NSString stringWithFormat:@"%d",_page],
                           @"perpage":@"10"
                           };
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(my_messageList_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            _totailPage = [responseObject[@"datas"][@"total_page"] integerValue];
            
            if (_page==1) {
                
                if (_dataArray) {
                    
                    [_dataArray removeAllObjects];
                }
                if ([responseObject[@"datas"][@"lists"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"datas"][@"lists"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }else {
                
                if ([responseObject[@"datas"][@"lists"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"datas"][@"lists"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                
                if (_dataArray.count>0) {
                    noBodyView.hidden =YES;
                    if (_dataArray.count<10) {
                        
                        _tableView.mj_footer.hidden = YES;
                    }else {
                        _tableView.mj_footer.hidden = NO;
                    }
                }else {
                    _tableView.mj_footer.hidden = YES;
                    noBodyView.hidden =NO;
                    
                    [self.view addSubview:noBodyView];
                }
                [_tableView.mj_header endRefreshing];
                [_tableView.mj_footer endRefreshing];
                [_tableView reloadData];
                
            });
            
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误请重试！");
    }];
    
    
}

-(void)deledateMessageRequestFor:(NSString *)str {
    
    NSDictionary * dic = @{@"mid":USER_DEFAULTGet(@"mid"),
                           @"token":USER_DEFAULTGet(@"token"),
                           @"msg_id":str
                           };
    
    [PostNetWorking postNetWorkingStr:RequestUrlStr(my_deledateMessage_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            
            SHuiMBhudTextTimeStr(@"删除成功");
            _page = 1;
            [self getMessageListData];
        }
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextNetError;
    }];
}



@end
